package com.zf.zfed.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.viewbinding.ViewBinding
import com.zf.zfed.audit.base.fragment.BaseLogicFragment
import com.zf.zfed.audit.tools.ViewManager
import com.zf.zfed.audit.utils.ReflectUtil

/**
 * @Author: wqq
 * @Date: 2023/3/6 9:11
 * @Description: 通用ViewModel Fragment
 * 包括ViewBinding
 * 以及自动创建viewModel
 * 以及viewModel的通用观察处理
 */
open class BaseViewModeFragment<VB : ViewBinding?> : BaseLogicFragment(), OnTouchListener {
    private var _binding: VB? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //调用inflate方法，创建viewBinding
        _binding = ReflectUtil.newViewBinding(layoutInflater, this.javaClass)

        ViewManager.registerView(this)
    }

    override fun getLayoutView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = binding.root
        view.setOnTouchListener(this)
        return view
    }

    override fun onDestroyView() {
        super.onDestroyView()
        ViewManager.unregisterView(this)
        _binding = null
    }

    /**
     * 给fragment增加findViewById
     */
    open fun <T : View?> findViewById(@IdRes id: Int): T {
        return binding.root.findViewById(id)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View, event: MotionEvent): Boolean {
        return true
    }
}